<script setup lang="ts">
import type { Recordable } from '@vben/types';

import { ref, computed, watch, h } from 'vue';

import { Page, useVbenDrawer, type VbenFormProps, confirm, prompt } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';

import { Modal, Popconfirm, Space, Tabs, Input, message } from 'ant-design-vue';
const { TabPane } = Tabs;
import dayjs from 'dayjs';

import {   
  useVbenVxeGrid,
  vxeCheckboxChecked,
  type VxeGridProps 
} from '#/adapter/vxe-table';

import {
  saleContractExport,
  saleContractList,
  saleContractRemove,
  saleContractSubmit,
  saleContractApprove,
} from '#/api/trade/saleContract';
import type { SaleContractForm } from '#/api/trade/saleContract/model';
import { commonDownloadExcel } from '#/utils/file/download';

import saleContractDrawer from './saleContract-drawer.vue';
import { columns, querySchema, getColumns } from './data';

// 销售合同状态定义
const CONTRACT_STATUS = {
  PENDING_SUBMIT: 'draft', // 待提交
  PENDING_REVIEW: 'waiting', // 待审核
  APPROVED: 'passed', // 已通过
  REJECTED: 'rejected', // 已驳回
  CANCELLED: 'invalid', // 已作废
};

// 状态标签页配置
const statusTabs = [
  { key: '', label: '全部' },
  { key: CONTRACT_STATUS.PENDING_SUBMIT, label: '待提交' },
  { key: CONTRACT_STATUS.PENDING_REVIEW, label: '待审核' },
  { key: CONTRACT_STATUS.APPROVED, label: '已通过' },
  { key: CONTRACT_STATUS.REJECTED, label: '已驳回' },
  { key: CONTRACT_STATUS.CANCELLED, label: '已作废' },
];

// 当前激活的状态tab
const activeStatus = ref('');

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // 处理区间选择器RangePicker时间格式 将一个字段映射为两个字段 搜索/导出会用到
  // 不需要直接删除
  // fieldMappingTime: [
  //  [
  //    'createTime',
  //    ['params[beginTime]', 'params[endTime]'],
  //    ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
  //  ],
  // ],
};

// 为每个状态创建独立的表格配置
const createGridOptions = (status: string): VxeGridProps => ({
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  // 根据状态动态生成列配置
  columns: getColumns(status),
  // height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const params = {
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        };
        // 只有当status不为空时才添加status参数
        if (status) {
          params.status = status;
        }
        return await saleContractList(params);
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到，每个状态tab使用不同的ID
  id: `trade-saleContract-${status}`
});

// 为每个状态创建独立的表格实例
const tableInstances = ref<Record<string, any>>({});

// 初始化所有状态的表格实例
statusTabs.forEach(tab => {
  const [BasicTable, tableApi] = useVbenVxeGrid({
    formOptions,
    gridOptions: createGridOptions(tab.key),
  });
  tableInstances.value[tab.key] = { BasicTable, tableApi };
});

// 获取当前激活状态的表格实例
const currentTableInstance = computed(() => {
  return tableInstances.value[activeStatus.value];
});

// 状态切换处理函数
function handleStatusChange(status: string) {
  activeStatus.value = status;
  tableInstances.value[status].tableApi.query();
}

const [SaleContractDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: saleContractDrawer,
});

function handleAdd() {
  // 添加新合同时，自动设置当前tab页对应的状态
  // 如果是"全部"tab页，则不设置状态，让用户自己选择
  const data = activeStatus.value ? { status: activeStatus.value } : {};
  drawerApi.setData(data);
  drawerApi.open();
}

async function handleEdit(row: Required<SaleContractForm>) {
  drawerApi.setData({ id: row.id });
  drawerApi.open();
}

async function handleDelete(row: Required<SaleContractForm>) {
  await saleContractRemove(row.id);
  await currentTableInstance.value.tableApi.query();
}

function handleMultiDelete() {
  const { tableApi } = currentTableInstance.value;
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Required<SaleContractForm>) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认作废选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await saleContractRemove(ids);
      await tableApi.query();
    },
  });
}

function handleDownloadExcel() {
  const { tableApi } = currentTableInstance.value;
  commonDownloadExcel(saleContractExport, '销售合同数据', tableApi.formApi.form.values, {
    fieldMappingTime: formOptions.fieldMappingTime,
  });
}

// 提交审核处理函数
function handleSubmitReview() {
  const { tableApi } = currentTableInstance.value;
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Required<SaleContractForm>) => row.id);
  Modal.confirm({
    title: '提示',
    content: `确认提交选中的${ids.length}条合同进行审核吗？`,
    onOk: async () => {
      await saleContractSubmit(ids);
      await tableApi.query();
    },
  });
}

// 批量审核通过处理函数
async function handleBatchApprove() {
  const { tableApi } = currentTableInstance.value;
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Required<SaleContractForm>) => row.id);
  
  try {
    await confirm({
      title: '批量审核通过',
      content: `确认通过选中的${ids.length}条合同吗？`,
    });
    
    for (const id of ids) {
      await saleContractApprove(id);
    }
    message.success('批量审核通过成功');
    await tableApi.query();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量审核通过失败:', error);
    }
  }
}

// 批量驳回处理函数
async function handleBatchReject() {
  const { tableApi } = currentTableInstance.value;
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: Required<SaleContractForm>) => row.id);
  
  try {
    const reason = await prompt({
      title: '批量驳回合同',
      content: '请输入驳回原因：',
      componentProps: {
        placeholder: '请输入驳回原因，不超过200字',
      },
    });
    
    if (!reason || !reason.trim()) {
      message.error('请输入驳回原因');
      return;
    }
    
    if (reason.trim().length > 200) {
      message.error('驳回原因不能超过200字');
      return;
    }
    
    for (const id of ids) {
      await saleContractReject({ id, rejectReason: reason.trim() });
    }
    message.success('批量驳回成功');
    await tableApi.query();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量驳回失败:', error);
    }
  }
}
</script>

<template>
  <Page :auto-content-height="true">
    <Tabs 
      v-model:activeKey="activeStatus" 
      @change="handleStatusChange"
      class="mb-4"
    >
      <TabPane 
        v-for="tab in statusTabs" 
        :key="tab.key" 
        :tab="tab.label"
      >
        <component 
          :is="tableInstances[tab.key].BasicTable" 
        >
          <template #toolbar-actions>
            <Space>
              <a-button
                v-access:code="['trade:saleContract:export']"
                @click="handleDownloadExcel"
              >
                {{ $t('pages.common.export') }}
              </a-button>
              <!-- 提交审核按钮，仅在待提交状态下显示 -->
              <a-button
                v-if="activeStatus === CONTRACT_STATUS.PENDING_SUBMIT"
                :disabled="!vxeCheckboxChecked(currentTableInstance.tableApi)"
                type="primary"
                v-access:code="['trade:saleContract:submit']"
                @click="handleSubmitReview"
              >
                提交审核
              </a-button>
              <!-- 批量审核通过按钮，仅在待审核状态下显示 -->
              <a-button
                v-if="activeStatus === CONTRACT_STATUS.PENDING_REVIEW"
                :disabled="!vxeCheckboxChecked(currentTableInstance.tableApi)"
                type="primary"
                v-access:code="['trade:saleContract:pass']"
                @click="handleBatchApprove"
              >
                批量通过
              </a-button>
              <!-- 批量驳回按钮，仅在待审核状态下显示 -->
              <a-button
                v-if="activeStatus === CONTRACT_STATUS.PENDING_REVIEW"
                :disabled="!vxeCheckboxChecked(currentTableInstance.tableApi)"
                danger
                v-access:code="['trade:saleContract:reject']"
                @click="handleBatchReject"
              >
                批量驳回
              </a-button>
              <!-- 批量删除按钮，仅在待提交和已作废状态下显示 -->
              <a-button
                v-if="activeStatus === CONTRACT_STATUS.PENDING_SUBMIT || activeStatus === CONTRACT_STATUS.CANCELLED"
                :disabled="!vxeCheckboxChecked(currentTableInstance.tableApi)"
                danger
                type="primary" 
                v-access:code="['trade:saleContract:remove']" 
                @click="handleMultiDelete">
                作废
              </a-button>
              <a-button
                type="primary"
                v-access:code="['trade:saleContract:add']"
                @click="handleAdd"
              >
                {{ $t('pages.common.add') }}
              </a-button>
            </Space>
          </template>
          <template #contractNo="{ row }">
            <a-button 
              type="link" 
              @click="handleEdit(row)"
              class="p-0 h-auto"
            >
              {{ row.contractNo }}
            </a-button>
          </template>

        </component>
      </TabPane>
    </Tabs>
    <SaleContractDrawer @reload="currentTableInstance.tableApi.query()" />
  </Page>
</template>
